package org.simple.rpc.service.proxy;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import net.sf.cglib.proxy.InvocationHandler;
import net.sf.cglib.proxy.Proxy;

import org.simple.rpc.load.hash.ProducerSharedUtils;
import org.simple.rpc.redis.utils.RedisKey;
import org.simple.rpc.redis.utils.RedisUtils;
import org.simple.rpc.service.base.RpcClient;
import org.simple.rpc.service.request.RpcRequest;
import org.simple.rpc.service.response.RpcResponse;
import org.simple.rpc.zookeeper.service.ZookeeperService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

@Component
public class RpcProxy {
	
	private Logger logger=LoggerFactory.getLogger(RpcProxy.class);
	
    
    @Autowired
    private ZookeeperService zookeeperService;
    
    @Autowired
	@Qualifier("nameSpace")
	private String nameSpace;
    
    @Autowired
	@Qualifier("clientPort")
    private String clientPort;


    @SuppressWarnings("unchecked")
    public <T> T create(Class<?> interfaceClass) {
        return (T) Proxy.newProxyInstance(
            interfaceClass.getClassLoader(),
            new Class<?>[]{interfaceClass},
            new InvocationHandler() {
                public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                    RpcRequest request = new RpcRequest(); // 创建并初始化 RPC 请求
                    request.setRequestId(UUID.randomUUID().toString());
                    request.setClassName(method.getDeclaringClass().getName());
                    request.setMethodName(method.getName());
                    request.setParameterTypes(method.getParameterTypes());
                    request.setParameters(args);

                    String[] array = getServerUrl().split(":");
                    String host = array[0];
                    int port = Integer.parseInt(array[1]);

                    RpcClient client = new RpcClient(host, port); // 初始化 RPC 客户端
                    RpcResponse response = client.send(request); // 通过 RPC 客户端发送 RPC 请求并获取 RPC 响应

//                    if (response.) {
//                        throw response.getError();
//                    } else {
                        return response.getResult();
                   // }
                }
            }
        );
    }
    
    private String getServerUrl(){
    	     ProducerSharedUtils producerSharedUtils=null;
    	     List<String> serverUrls=RedisUtils.getList(RedisKey.SERVER_URL_KEY);
    	      if(serverUrls!=null&&serverUrls.size()>0){
    	    	  producerSharedUtils =new ProducerSharedUtils(serverUrls);  
    	      }else{
    	    	  //获得缓存中的负载info
        		  if (zookeeperService.isConnected()) {
        			    List<String> serverNodes=zookeeperService.getChilds(nameSpace);
        	         	logger.info(" server nodes===>>>>>"+serverNodes.toString());
        	         	serverUrls= zookeeperService.getChildDatas(nameSpace, serverNodes);
        	         	RedisUtils.setList(RedisKey.SERVER_URL_KEY, serverUrls);
        	         }else{
        	        	 throw new Error("zookeeper lose link....");
        	         }
        		  producerSharedUtils =new ProducerSharedUtils(serverUrls);
    	      }
    	    
    	return producerSharedUtils.getServerUrlInfo(clientPort);
    }
    
}
